<template>
  <div class="category-add-container">
    <div class="add-card">
      <h2 class="add-title">分类管理</h2>

      <form @submit.prevent="handleSubmit" class="add-form">
        <!-- 操作类型选择 -->
        <div class="form-group">
          <label class="form-label">操作类型</label>
          <div class="operation-selector">
            <div
              class="operation-option"
              :class="{ 'selected': operationType === 'new-category' }"
              @click="operationType = 'new-category'"
            >
              <div class="option-icon">📁</div>
              <div class="option-info">
                <div class="option-name">创建一级分类</div>
                <div class="option-desc">创建全新的分类</div>
              </div>
            </div>
            <div
              class="operation-option"
              :class="{ 'selected': operationType === 'add-subcategory' }"
              @click="operationType = 'add-subcategory'"
            >
              <div class="option-icon">📂</div>
              <div class="option-info">
                <div class="option-name">添加子分类</div>
                <div class="option-desc">为现有分类添加子分类</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 选择现有一级分类（仅在添加子分类时显示） -->
        <div v-if="operationType === 'add-subcategory'" class="form-group">
          <label for="parentCategory" class="form-label">选择一级分类 *</label>
          <select
            id="parentCategory"
            v-model="formData.id"
            class="form-select"
            required
          >
            <option value="">请选择一级分类</option>
            <option
              v-for="category in categories"
              :key="category.categoryId"
              :value="category.categoryId"
            >
              {{ category.name }} ({{ category.description }})
            </option>
          </select>
          <div class="form-hint">选择要添加子分类的一级分类</div>
        </div>

        <!-- 一级分类名称 -->
        <div v-if="operationType === 'new-category'" class="form-group">
          <label for="categoryName" class="form-label">一级分类名称 *</label>
          <input
            id="categoryName"
            v-model="formData.name"
            type="text"
            class="form-input"
            placeholder="请输入分类名称"
            required
          />
        </div>

        <!-- 一级分类描述 -->
        <div v-if="operationType === 'new-category'" class="form-group">
          <label for="categoryDesc" class="form-label">一级分类描述</label>
          <textarea
            id="categoryDesc"
            v-model="formData.description"
            class="form-textarea"
            placeholder="请输入分类描述"
            rows="3"
          ></textarea>
        </div>

        <!-- 是否同时添加子分类 -->
        <div v-if="operationType === 'new-category'" class="form-group">
          <label class="form-label">
            <input
              type="checkbox"
              v-model="addSubCategory"
              class="form-checkbox"
            />
            同时创建子分类
          </label>
          <div class="form-hint">勾选此项可以在创建一级分类的同时添加子分类</div>
        </div>

        <!-- 子分类信息（在添加子分类或勾选同时创建时显示） -->
        <div v-if="operationType === 'add-subcategory' || (operationType === 'new-category' && addSubCategory)" class="subcategory-section">
          <h3 class="section-title">子分类信息</h3>

          <div class="form-group">
            <label for="subCategoryName" class="form-label">子分类名称 *</label>
            <input
              id="subCategoryName"
              v-model="formData.subCategoryName"
              type="text"
              class="form-input"
              placeholder="请输入子分类名称"
              required
            />
          </div>

          <div class="form-group">
            <label for="subCategoryDesc" class="form-label">子分类描述</label>
            <textarea
              id="subCategoryDesc"
              v-model="formData.subCategoryDescription"
              class="form-textarea"
              placeholder="请输入子分类描述"
              rows="3"
            ></textarea>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button
            type="button"
            @click="resetForm"
            class="reset-btn"
            :disabled="isSubmitting"
          >
            重置表单
          </button>
          <button
            type="submit"
            class="submit-btn"
            :disabled="isSubmitting || !isFormValid"
          >
            <span v-if="isSubmitting">提交中...</span>
            <span v-else>{{ submitButtonText }}</span>
          </button>
        </div>
      </form>

      <!-- 成功提示 -->
      <div v-if="successMessage" class="success-message">
        {{ successMessage }}
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>

      <!-- 分类列表预览 -->
      <div v-if="categories.length > 0" class="categories-preview">
        <h3 class="section-title">现有分类</h3>
        <div class="category-list">
          <div
            v-for="category in categories"
            :key="category.categoryId"
            class="category-item"
          >
            <div class="category-header">
              <span class="category-name">{{ category.name }}</span>
              <span class="category-desc">{{ category.description }}</span>
            </div>
            <div v-if="category.subCategories.length > 0" class="subcategory-list">
              <div
                v-for="subCategory in category.subCategories"
                :key="subCategory.subCategoryId"
                class="subcategory-item"
              >
                <span class="subcategory-name">└ {{ subCategory.name }}</span>
                <span class="subcategory-desc">{{ subCategory.description }}</span>
              </div>
            </div>
            <div v-else class="no-subcategories">
              暂无子分类
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

// 类型定义
interface SubCategory {
  subCategoryId: number
  name: string
  description: string
  coverImage: string | null
}

interface Category {
  categoryId: number
  name: string
  description: string
  coverImage: string | null
  subCategories: SubCategory[]
}

interface CategoryAddDTO {
  id?: number
  name?: string
  description?: string
  subCategoryName?: string
  subCategoryDescription?: string
}

// 常量
const API_BASE_URL = 'http://web.xiaowang.link:18001/api'
const AUTH_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIsImNyZWF0ZVRpbWUiOjE3NDk5Njg2OTd9.5tMXRtOL5NYxOsSeeOiX8v2xPPtGAvDgAsGKrDKByN4'

// 响应式数据
const operationType = ref<'new-category' | 'add-subcategory'>('new-category')
const addSubCategory = ref(false)
const categories = ref<Category[]>([])
const isSubmitting = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

const formData = ref<CategoryAddDTO>({
  id: undefined,
  name: '',
  description: '',
  subCategoryName: '',
  subCategoryDescription: ''
})

// 计算属性
const isFormValid = computed(() => {
  if (operationType.value === 'new-category') {
    const hasRequiredFields = formData.value.name?.trim()
    if (addSubCategory.value) {
      return hasRequiredFields && formData.value.subCategoryName?.trim()
    }
    return hasRequiredFields
  } else {
    return formData.value.id && formData.value.subCategoryName?.trim()
  }
})

const submitButtonText = computed(() => {
  if (operationType.value === 'new-category') {
    return addSubCategory.value ? '创建分类及子分类' : '创建分类'
  } else {
    return '添加子分类'
  }
})

// 方法
const fetchCategories = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/categories`, {
      headers: {
        'Authorization': `Bearer ${AUTH_TOKEN}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取分类失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      categories.value = result.data
    } else {
      throw new Error(result.message || '获取分类失败')
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    errorMessage.value = `获取分类失败: ${error instanceof Error ? error.message : '未知错误'}`
  }
}

const handleSubmit = async () => {
  if (!isFormValid.value) return

  isSubmitting.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const submitData: CategoryAddDTO = {}

    if (operationType.value === 'new-category') {
      // 创建新的一级分类
      submitData.name = formData.value.name
      submitData.description = formData.value.description

      if (addSubCategory.value) {
        submitData.subCategoryName = formData.value.subCategoryName
        submitData.subCategoryDescription = formData.value.subCategoryDescription
      }
    } else {
      // 为现有分类添加子分类
      submitData.id = formData.value.id
      submitData.subCategoryName = formData.value.subCategoryName
      submitData.subCategoryDescription = formData.value.subCategoryDescription
    }

    console.log('提交数据:', submitData)

    const response = await fetch(`${API_BASE_URL}/categories/add`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${AUTH_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      successMessage.value = `${submitButtonText.value}成功！`
      resetForm()
      // 重新获取分类列表
      await fetchCategories()
    } else {
      throw new Error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    errorMessage.value = `操作失败: ${error instanceof Error ? error.message : '未知错误'}`
  } finally {
    isSubmitting.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    description: '',
    subCategoryName: '',
    subCategoryDescription: ''
  }
  addSubCategory.value = false
  operationType.value = 'new-category'
  successMessage.value = ''
  errorMessage.value = ''
}

// 生命周期
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-add-container {
  width: 100%;
  margin: 0;
  padding: 2rem;
}

.add-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 2.5rem;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.add-title {
  text-align: center;
  color: #333;
  margin-bottom: 2rem;
  font-size: 2rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.add-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-label {
  font-weight: 600;
  color: #555;
  margin-bottom: 0.5rem;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.form-checkbox {
  margin-right: 0.5rem;
}

.operation-selector {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-top: 0.5rem;
}

.operation-option {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.operation-option:hover {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.operation-option.selected {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.option-icon {
  font-size: 2rem;
  min-width: 2rem;
}

.option-info {
  flex: 1;
}

.option-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.25rem;
}

.option-desc {
  font-size: 0.85rem;
  color: #666;
  line-height: 1.4;
}

.form-input,
.form-textarea,
.form-select {
  padding: 0.75rem;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background: white;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-hint {
  margin-top: 0.5rem;
  color: #6b7280;
  font-size: 0.85rem;
}

.subcategory-section {
  background: #f8fafc;
  border-radius: 12px;
  padding: 1.5rem;
  border: 1px solid #e2e8f0;
}

.section-title {
  color: #374151;
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 1rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.reset-btn,
.submit-btn {
  flex: 1;
  padding: 1rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reset-btn {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.reset-btn:hover:not(:disabled) {
  background: #e5e7eb;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.submit-btn:disabled,
.reset-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.success-message {
  margin-top: 1.5rem;
  padding: 1rem;
  background: #f0fdf4;
  color: #166534;
  border-radius: 8px;
  border: 1px solid #bbf7d0;
}

.error-message {
  margin-top: 1.5rem;
  padding: 1rem;
  background: #fef2f2;
  color: #dc2626;
  border-radius: 8px;
  border: 1px solid #fecaca;
}

.categories-preview {
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #e5e7eb;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.category-item {
  background: #f9fafb;
  border-radius: 8px;
  padding: 1rem;
  border: 1px solid #e5e7eb;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.category-name {
  font-weight: 600;
  color: #374151;
}

.category-desc {
  color: #6b7280;
  font-size: 0.875rem;
}

.subcategory-list {
  margin-left: 1rem;
}

.subcategory-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid #f3f4f6;
}

.subcategory-item:last-child {
  border-bottom: none;
}

.subcategory-name {
  color: #4b5563;
  font-size: 0.875rem;
}

.subcategory-desc {
  color: #9ca3af;
  font-size: 0.8rem;
}

.no-subcategories {
  color: #9ca3af;
  font-size: 0.875rem;
  font-style: italic;
  margin-left: 1rem;
}

@media (max-width: 768px) {
  .category-add-container {
    padding: 1rem;
  }

  .add-card {
    padding: 1.5rem;
  }

  .operation-selector {
    grid-template-columns: 1fr;
  }

  .form-actions {
    flex-direction: column;
  }

  .category-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }
}
</style>
